package com.cowin.base;

import com.cowin.base.result.Result;
import com.cowin.base.result.ResultGenerator;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * Copyright (C), 1998-2018, 奇瑞信息
 *
 * @author : 于超
 * @Date: 2019/8/29 17:26
 * @Description:
 */
public abstract class BaseController<T> {
    @Autowired
    private Service<T> service;

    @GetMapping
    @ApiOperation(value = "查询所有", notes = "查询所有")
    public Result getAll(@RequestParam(defaultValue = "0") Integer page, @RequestParam(defaultValue = "0") Integer size) {
        PageHelper.startPage(page, size);
        List<T> list = service.findAll();
        PageInfo<T> pageInfo = new PageInfo<>(list);
        return ResultGenerator.genSuccessResult(pageInfo);
    }

    @GetMapping("/{id}")
    @ApiOperation(value = "id 查询", notes = "id 查询")
    public Result detail(@PathVariable Integer id) {
        T entity = service.findById(id);
        return ResultGenerator.genSuccessResult(entity);
    }

    @PostMapping
    @ApiOperation(value = "新增", notes = "新增")
    public Result add(@RequestBody T entity) {
        int count = service.save(entity);
        if (count > 0) {
            return ResultGenerator.genSuccessResult(entity);
        }
        return ResultGenerator.genFailResult("删除" + count + "行");
    }

    @DeleteMapping("/{id}")
    @ApiOperation(value = "id 删除", notes = "删除")
    public Result delete(@PathVariable Integer id) {
        int count = service.deleteById(id);
        if (count > 0) {
            return ResultGenerator.genSuccessResult();
        }
        return ResultGenerator.genFailResult("删除" + count + "行");
    }

    @PutMapping
    @ApiOperation(value = "更新", notes = "更新")
    public Result update(@RequestBody T entity) {
        int count = service.update(entity);
        if (count > 0) {
            return ResultGenerator.genSuccessResult(entity);
        }
        return ResultGenerator.genFailResult("更新" + count + "行");
    }


}

